package com.ml.mall.service.asyn;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ml.mall.bean.req.company.CompanyDto;
import com.ml.mall.bean.req.order.OrderEditReq;
import com.ml.mall.bean.req.vo.OrderMailTemplateVO;
import com.ml.mall.bean.res.company.CompanyQueryInfoRes;
import com.ml.mall.bean.vo.OrderDetailArrVO;
import com.ml.mall.bean.vo.coupon.CupponDetailVO;
import com.ml.mall.consts.*;
import com.ml.mall.entity.company.SysCompany;
import com.ml.mall.entity.coupon.SysCoupon;
import com.ml.mall.entity.delivery.SysOrderDelivery;
import com.ml.mall.entity.detail.SysOrderDetail;
import com.ml.mall.entity.msg.SysOrderMsg;
import com.ml.mall.entity.order.SysOrder;
import com.ml.mall.entity.payinfo.SysPayinfo;
import com.ml.mall.entity.state.SysOrderState;
import com.ml.mall.entity.supplier.SysOrderSupplier;
import com.ml.mall.entity.sys.SysUser;
import com.ml.mall.entity.variant.SysProductVariant;
import com.ml.mall.entity.variant.SysProductVariantSku;
import com.ml.mall.mapper.company.SysCompanyLogisticsInfoMapper;
import com.ml.mall.mapper.company.SysCompanyMapper;
import com.ml.mall.mapper.coupon.SysCouponMapper;
import com.ml.mall.mapper.coupon.SysCouponRecordMapper;
import com.ml.mall.mapper.delivery.SysOrderDeliveryMapper;
import com.ml.mall.mapper.detail.SysOrderDetailMapper;
import com.ml.mall.mapper.order.SysOrderMapper;
import com.ml.mall.mapper.state.SysOrderStateMapper;
import com.ml.mall.mapper.supplier.SysOrderSupplierMapper;
import com.ml.mall.model.MailMessage;
import com.ml.mall.service.company.SysCompanyService;
import com.ml.mall.service.coupon.SysCouponRecordService;
import com.ml.mall.service.mail.MailService;
import com.ml.mall.service.msg.SysOrderMsgService;
import com.ml.mall.service.notifation.SysANotifationService;
import com.ml.mall.service.sys.SysUserService;
import com.ml.mall.service.variant.SysProductVariantService;
import com.ml.mall.service.variant.SysProductVariantSkuService;
import com.ml.mall.utils.MailTemplateUtils;
import com.ml.mall.utils.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by kyyang on 2021/7/27 23:25
 */
@Component
@Slf4j
public class OrderMailServiceImplAsyn {

    @Autowired
    private MailService mailService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysProductVariantSkuService sysProductVariantSkuService;

    @Autowired
    private SysCompanyService sysCompanyService;

    @Autowired
    private SysProductVariantService sysProductVariantService;

    @Autowired
    private SysOrderSupplierMapper sysOrderSupplierMapper;

    @Autowired
    private SysOrderMapper sysOrderMapper;

    @Autowired
    private SysOrderStateMapper sysOrderStateMapper;

    @Autowired
    private SysOrderDetailMapper sysOrderDetailMapper;

    @Autowired
    private SysOrderDeliveryMapper sysOrderDeliveryMapper;

    @Autowired
    private SysCouponMapper sysCouponMapper;
    @Autowired
    private SysCompanyMapper sysCompanyMapper;

    @Autowired
    private SysCouponRecordMapper sysCouponRecordMapper;

    @Autowired
    private SysCompanyLogisticsInfoMapper sysCompanyLogisticsInfoMapper;

    @Autowired
    private SysANotifationService sysANotifationService;

    @Autowired
    private SysCouponRecordService sysCouponRecordService;

    @Autowired
    private SysOrderMsgService sysOrderMsgService;


    /**
     * 新建订单发送邮件，通知管理员
     * @param currentUser
     * @param orderMailTemplateVO
     */
    @Async
    public void sysOrderNewMailAsyn(SysUser currentUser,OrderMailTemplateVO orderMailTemplateVO) {
        MailMessage mailMessage = new MailMessage();
        //查询备注信息
        QueryWrapper<SysOrderMsg> queryWrapper=new QueryWrapper<SysOrderMsg>()
                .eq("oid",orderMailTemplateVO.getOid());
        SysOrderMsg sysOrderMsg = sysOrderMsgService.getOne(queryWrapper);
        MailTemplateUtils mailTemplateUtils=new MailTemplateUtils();
        StringBuilder sb=mailTemplateUtils.MailTeplate(orderMailTemplateVO,currentUser,sysOrderMsg);
        mailMessage.setContent(sb.toString());
        //标题替换
        //设置模板标题
        mailMessage.setSubject("New purchase order  purchase_order_no  has been made.");
        mailMessage.subjectReplace("purchase_order_no", orderMailTemplateVO.getOid().toString());
        //内容替换
        mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
        mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("SYSTEM_URL",MailContentConsts.SYSTEM_URL));

        //需要使用订单邮件作为发送方邮件
        mailMessage.setInformType(MailConstants.ORDER_TYPE);
        if(mailMessage!=null){
            //发送给当前用户
            mailMessage.setReceiverEmail(currentUser.getEmail());
            mailMessage.setContent(mailMessage.getContent().replaceAll("USERNAME",currentUser.getName()));
            MailUtils.doSendEmail1(mailMessage);

            //通知管理员
            sysANotifationService.notifyAdmin(mailMessage);
            //发送邮件给管理员
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("role_type",1);
            wrapper.in("role_id", Arrays.asList(new Integer[]{1,2,3}));
            List<SysUser> list = sysUserService.list(wrapper);
            if(list!=null&&list.size()>0){
                for(SysUser u:list){
                    mailMessage.setReceiverEmail(u.getEmail());
                    mailMessage.setContent(mailMessage.getContent().replace("USERNAME",u.getName()));
                    MailUtils.doSendEmail1(mailMessage);
                }
            }
        }
    }

    /**
     * @description: 卖家 state = 2 接收邮件 7 拒绝,通知管理员和买家
     * @author kyyang
     * @date 2021/7/28 23:22
     * @version 1.0
     */
    @Async
    public void sysOrderSupplierEditStateMailAsyn(SysUser sysUser,OrderEditReq orderEditReq) {
        SysOrderSupplier sysOrderSupplier = sysOrderSupplierMapper.selectById(orderEditReq.getId());
        if(sysOrderSupplier==null){
            return;
        }
        SysOrder sysOrder = sysOrderMapper.selectOrderByOid(sysOrderSupplier.getOid());
        //这里会检测是否所有订单都完成；都完成才会触发完成订单的通知
        if(sysOrderSupplier.getState().equals(SupplierOrderStateConsts.ORDER_STATE_COMPLETE)){
            //全部订单都已完成才完成
            sendForPurchaseOrderCompleted(sysOrderSupplier);
        }else if(sysOrderSupplier.getState().equals(SupplierOrderStateConsts.ORDER_STATE_SHIPPED)){ //发货
            //只通知处理中与已发货
            sendForDeliveryScheduleUpdatedByEachSupplier(sysOrder,sysOrderSupplier);
        }else if(sysOrderSupplier.getState().equals(SupplierOrderStateConsts.ORDER_STATE_PROCESS)){ //接受
            //通知买家
//            sendForDeliveryScheduleUpdatedByEachSupplier(sysOrder,sysOrderSupplier);
            //通知管理员
            sendForSupplierChangeOrderToAdmin(sysUser, sysOrderSupplier);
        }else if(sysOrderSupplier.getState().equals(SupplierOrderStateConsts.ORDER_STATE_REJECT)){ //拒绝
            //通知管理员
            sendForSupplierChangeOrderToAdmin(sysUser, sysOrderSupplier);
        }

  }

  //卖家接受或拒绝订单通知管理员
   private void sendForSupplierChangeOrderToAdmin(SysUser sysUser,SysOrderSupplier sysOrderSupplier){
       MailMessage mailMessage;
       if(sysOrderSupplier.getState().equals(SupplierOrderStateConsts.ORDER_STATE_REJECT)){
           mailMessage =  mailService.sendForSupplierRejectPurchaseOrder("");
       }else{
           mailMessage =  mailService.sendForSupplierAcceptPurchaseOrder("");
       }
       //设置标题
       mailMessage.setSubject(mailMessage.getSubject().replace("order_no",sysOrderSupplier.getOid()+""));
       mailMessage.setSubject(mailMessage.getSubject().replace("company_name",sysUser.getCompanyName()));
       //设置内容
       mailMessage.setContent(mailMessage.getContent().replace("order_no",sysOrderSupplier.getOid()+""));
       mailMessage.setContent(mailMessage.getContent().replace("company_name",sysUser.getCompanyName()));
       mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
       mailMessage.setContent(mailMessage.getContent().replaceAll("system_url",MailContentConsts.SYSTEM_URL));
       mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
       mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
       //需要使用订单邮件作为发送方邮件
       mailMessage.setInformType(MailConstants.ORDER_TYPE);
       //创建通知：通知管理员
       sysANotifationService.notifyAdmin(mailMessage);
       //发送邮件
       QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
       wrapper.in("role_id", Arrays.asList(new Integer[]{1,2,3,4,5}));
       List<SysUser> list = sysUserService.list(wrapper);
       if(list!=null&&list.size()>0){
           for(SysUser u:list){
               mailMessage.setReceiverEmail(u.getEmail());
               mailMessage.setContent(mailMessage.getContent().replace("admin_name",u.getName()));
               MailUtils.doSendEmail1(mailMessage);
           }
       }
   }
//   订单状态更改；通知买家
    private void sendForDeliveryScheduleUpdatedByEachSupplier(SysOrder sysOrder, SysOrderSupplier sysOrderSupplier) {
        MailMessage mailMessage = mailService.sendForDeliveryScheduleUpdatedByEachSupplier("");
        mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("system_url",MailContentConsts.SYSTEM_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
        mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
        mailMessage.setContent(mailMessage.getContent().replace("order_no",sysOrder.getOid()+""));
        //修改订单状态 处理
        String orderStatus = "process";
        if(sysOrderSupplier.getState()==3){
            orderStatus = "shipped";
        }
        mailMessage.setContent(mailMessage.getContent().replace("order_state",orderStatus));

        //需要使用订单邮件作为发送方邮件
        mailMessage.setInformType(MailConstants.ORDER_TYPE);
        if(mailMessage!=null){
            //通知买家
            sysANotifationService.notifyCompany(mailMessage, sysOrder.getCompanyId());
            //发送邮件
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("company_id",sysOrder.getCompanyId());
            wrapper.in("role_id", Arrays.asList(new Integer[]{12,13,15}));
            List<SysUser> list1 = sysUserService.list(wrapper);
            log.info("list1==33={}",list1);
            if(list1!=null&&list1.size()>0){
                for(SysUser u:list1){
                    mailMessage.setReceiverEmail(u.getEmail());
                    mailMessage.setContent(mailMessage.getContent().replace("purchaser_name",u.getName()));
                    MailUtils.doSendEmail1(mailMessage);
                }
            }

        }
    }

//   订单完成
    private void sendForPurchaseOrderCompleted(SysOrderSupplier sysOrderSupplier) {
        QueryWrapper<SysOrderSupplier> wapper = new QueryWrapper<>();
        wapper.eq("oid",sysOrderSupplier.getOid());
        List<SysOrderSupplier> list = sysOrderSupplierMapper.selectList(wapper);
        if(list!=null&&list.size()>0){
            for(SysOrderSupplier so:list){
                if(!so.getState().equals(SupplierOrderStateConsts.ORDER_STATE_COMPLETE)){
                    return;
                }
            }
            //检测买家订单是否已经完成
            SysOrder sysOrder1 = sysOrderMapper.selectOrderByOid(sysOrderSupplier.getOid());
            if(!sysOrder1.getState().equals(OrderStateConsts.ORDER_STATE_COMPLETE)){
                return;
            }

            MailMessage mailMessage = mailService.sendForPurchaseOrderCompleted("");
            mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
            mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
            mailMessage.setContent(mailMessage.getContent().replaceAll("system_url",MailContentConsts.SYSTEM_URL));
            mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
            mailMessage.setContent(mailMessage.getContent().replace("order_no",sysOrder1.getOid()+""));
            //需要使用订单邮件作为发送方邮件
            mailMessage.setInformType(MailConstants.ORDER_TYPE);
            if(mailMessage!=null){
                //通知买家
                sysANotifationService.notifyCompany(mailMessage, sysOrder1.getCompanyId());
                //发送邮件
                QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
                wrapper.eq("company_id",sysOrder1.getCompanyId());
                wrapper.in("role_id", Arrays.asList(new Integer[]{12,13,15}));
                List<SysUser> list1 = sysUserService.list(wrapper);
                if(list1!=null&&list1.size()>0){
                    for(SysUser u:list1){
                        mailMessage.setReceiverEmail(u.getEmail());
                        mailMessage.setContent(mailMessage.getContent().replace("purchaser_name",u.getName()));
                        MailUtils.doSendEmail1(mailMessage);
                    }
                }

            }


        }
    }

    /**
     * @description: 低库存提醒  以及 0库存提醒 通知供应商
     * @author kyyang
     * @date 2021/8/1 16:28
     * @version 1.0
     */
    @Async
    public void checkSupplierInverntory(List<SysOrderDetail> orderDetails) {
        MailMessage mailMessage = mailService.sendForLowStockNotification("");
        //需要使用订单邮件作为发送方邮件
        mailMessage.setInformType(MailConstants.ORDER_TYPE);
        mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
        if(orderDetails!=null&&orderDetails.size()>0){
            for(SysOrderDetail sysOrderDetail:orderDetails){
                Long variantId = sysOrderDetail.getVariantId();
                Long supplierId = sysOrderDetail.getSupplierId();
                SysProductVariantSku sysProductVariantSku = sysProductVariantSkuService.getSkuByVariantId(variantId);
                if(sysProductVariantSku!=null && sysProductVariantSku.getStock()<=sysProductVariantSku.getLowStock()){
                    if(sysProductVariantSku.getStock()<=0){
                        sendZeroStock(orderDetails);
                        return;
                    }
                    CompanyDto dto = new CompanyDto();
                    dto.setCompanyId(supplierId);
                    CompanyQueryInfoRes companyQueryInfoRes = sysCompanyService.queryOneCompany(dto);
                    if(companyQueryInfoRes!=null){
                        String companyName = companyQueryInfoRes.getCompanyName();
                        mailMessage.setContent(mailMessage.getContent().replace("supplier_name",companyName));
                        QueryWrapper<SysProductVariant> wp = new QueryWrapper<>();
                        wp.eq("variant_id",variantId);
                        wp.eq("expiry_dt",new Date(CommonConsts.MAX_EXPIRY_TIME));
                        SysProductVariant one1 = sysProductVariantService.getOne(wp);
                        String name = "";
                        if(one1!=null){
                            name = one1.getVariantName();
                        }
                        mailMessage.setContent(mailMessage.getContent().replace("product_variant_name",name));

                        if(mailMessage!=null){
                            //通知供应商
                            sysANotifationService.notifyCompany(mailMessage, supplierId);
                            //发送邮件
                            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
                            wrapper.in("role_id", Arrays.asList(new Integer[]{8,9,11}));
                            wrapper.eq("company_id",supplierId);
                            List<SysUser> list = sysUserService.list(wrapper);
                            if(list!=null&&list.size()>0){
                                for(SysUser u:list){
                                    mailMessage.setReceiverEmail(u.getEmail());
                                    MailUtils.doSendEmail1(mailMessage);
                                }
                            }

                        }
                    }
                }
            }
        }




    }

    /**
     * @description: 零库存提醒 通知供应商
     * @author kyyang
     * @date 2021/8/1 21:03
     * @version 1.0
     */
    private void sendZeroStock(List<SysOrderDetail> orderDetails) {
        MailMessage  mailMessage= mailService.sendForOutOfStockNotification("");
        for(SysOrderDetail sysOrderDetail:orderDetails) {
            Long variantId = sysOrderDetail.getVariantId();
            Long supplierId = sysOrderDetail.getSupplierId();
            mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
            mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
            mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no", MailContentConsts.CONCAT));
            CompanyDto dto = new CompanyDto();
            dto.setCompanyId(supplierId);
            CompanyQueryInfoRes companyQueryInfoRes = sysCompanyService.queryOneCompany(dto);
            if (companyQueryInfoRes != null) {
                String companyName = companyQueryInfoRes.getCompanyName();
                mailMessage.setContent(mailMessage.getContent().replace("supplier_name", companyName));
                QueryWrapper<SysProductVariant> wp = new QueryWrapper<>();
                wp.eq("variant_id", variantId);
                wp.eq("expiry_dt", new Date(CommonConsts.MAX_EXPIRY_TIME));
                SysProductVariant one1 = sysProductVariantService.getOne(wp);
                String name = "";
                if (one1 != null) {
                    name = one1.getVariantName();
                }
                mailMessage.setContent(mailMessage.getContent().replace("product_variant_name", name));
                //需要使用订单邮件作为发送方邮件
                mailMessage.setInformType(MailConstants.ORDER_TYPE);
                if (mailMessage != null) {
                    //通知供应商
                    sysANotifationService.notifyCompany(mailMessage, supplierId);
                    //发送邮件
                    QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
                    wrapper.in("role_id", Arrays.asList(new Integer[]{8, 9, 11}));
                    wrapper.eq("company_id", supplierId);
                    List<SysUser> list = sysUserService.list(wrapper);
                    if (list != null && list.size() > 0) {
                        for (SysUser u : list) {
                            mailMessage.setReceiverEmail(u.getEmail());
                            MailUtils.doSendEmail1(mailMessage);
                        }
                    }
                }
            }
        }
    }

    /**
     * @description: 【邮件】卖家：新订单产生，通知卖家
     * @author kyyang
     * @date 2021/8/7 22:22
     * @version 1.0
     */
    @Async
    public void createVendorOrderMailAsyn(SysOrderSupplier sysOrderSupplier,List<SysOrderDetail> sysOrderDetails) {
        //查询优惠卷集合
        List<CupponDetailVO> cupponDetailVOList=sysCouponRecordService.cupponDetailVOList(sysOrderSupplier.getOid(),sysOrderSupplier.getSupplierId());
        //查询备注信息
        QueryWrapper<SysOrderMsg> queryWrapper=new QueryWrapper<SysOrderMsg>()
                .eq("oid",sysOrderSupplier.getOid());
        SysOrderMsg sysOrderMsg = sysOrderMsgService.getOne(queryWrapper);
        StringBuilder content= MailTemplateUtils.MailSupplierTeplate(sysOrderSupplier,sysOrderDetails,cupponDetailVOList,sysOrderMsg);
        MailMessage mailMessage=new MailMessage();
        mailMessage.setContent(content.toString());
        //MailUtils.doSendEmail1(mailMessage);
        //标题替换
        //设置模板标题
        mailMessage.setSubject("New purchase order  purchase_order_no  has been made.");
        mailMessage.subjectReplace("purchase_order_no", sysOrderSupplier.getSupplierOid().toString());
        //内容替换
        mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
        mailMessage.setContent(mailMessage.getContent().replaceAll("general_email", MailContentConsts.GENERAL_EMAIL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("SYSTEM_URL",MailContentConsts.SYSTEM_URL));

        //需要使用订单邮件作为发送方邮件
        mailMessage.setInformType(MailConstants.ORDER_TYPE);
        if(mailMessage!=null){
            //发送邮件
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.in("role_id", Arrays.asList(new Integer[]{8,9,10,11}));
            wrapper.eq("company_id",sysOrderSupplier.getSupplierId());
            List<SysUser> list = sysUserService.list(wrapper);
            if(list!=null&&list.size()>0){
                for(SysUser u:list){
                    mailMessage.setReceiverEmail(u.getEmail());
                    mailMessage.setContent(mailMessage.getContent().replace("USERNAME",u.getName()));
                    MailUtils.doSendEmail1(mailMessage);
                }
            }

        }
    }

    /**
     * @description: 【邮件】买家：订单支付成功,不发送邮件,通知买家
     * @param companyId
     */
    @Async
    public void createPurchaseOrderPaymentMadeMailAsyn(Long companyId){
        MailMessage mailMessage = mailService.sendForPurchaseOrderPaymentMade("");
        sysANotifationService.notifyCompany(mailMessage, companyId);
    }
}
